package com.wxb.testinterface.controller;

import com.wxb.apiclientsdk.model.YoudaoRequest;
import com.wxb.testinterface.utils.youdao.AuthV3Util;
import com.wxb.testinterface.utils.youdao.HttpUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/youdao")
public class YoudaoController {
    private static final String APP_KEY = "3ed473afdddfff95";     // 您的应用ID
    private static final String APP_SECRET = "XkxAoU5cb0FOuZRY25FVDgatwxmlkUuj";

    @PostMapping("")
    public String textTranslate(@RequestBody String requestParams) throws NoSuchAlgorithmException {
        YoudaoRequest youdaoRequest = new YoudaoRequest();
        youdaoRequest.setFrom("auto");
        youdaoRequest.setQ(requestParams);
        youdaoRequest.setTo("chinese");
        youdaoRequest.setVocabId("out_id");
        // 添加请求参数
        Map<String, String[]> params = createRequestParams(youdaoRequest);
        // 添加鉴权相关参数
        AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params);
        // 请求api服务
        byte[] result = HttpUtil.doPost("https://openapi.youdao.com/api", null, params, "application/json");
        String resultString = new String(result, StandardCharsets.UTF_8);
        String explains = resultString.substring(resultString.indexOf("explains"), resultString.indexOf("us-speech"));
        return explains;
//        return new String(result, StandardCharsets.UTF_8);
    }

    private static Map<String, String[]> createRequestParams(YoudaoRequest youdaoRequest) {

        String q = youdaoRequest.getQ();
        String from = youdaoRequest.getFrom();
        String to = youdaoRequest.getTo();
        String vocabId =youdaoRequest.getVocabId();

        return new HashMap<String, String[]>() {{
            put("q", new String[]{q});
            put("from", new String[]{from});
            put("to", new String[]{to});
            put("vocabId", new String[]{vocabId});
        }};
    }

}
